package com.example.demo48httpslogin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    @Bean
    protected UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager userDetailsManager = new InMemoryUserDetailsManager();
        userDetailsManager.createUser(User.withUsername("wangnian").password("{noop}123").roles("admin").build());
        return userDetailsManager;
    }

    /**
     * requiresChannel()：启用通道安全配置。
     * antMatchers("/http").requiresInsecure()：指定路径/http必须通过不安全的通道（即HTTP）访问。
     * antMatchers("/https").requiresSecure()：指定路径/https必须通过安全的通道（即HTTPS）访问。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin()
                .and()
                .requiresChannel()
                .antMatchers("/http").requiresInsecure()
                .antMatchers("/https").requiresSecure()
                .and().csrf().disable();
    }
}
